<template>
  <div>
    <el-container class="order-container">
      <el-header style="margin-top: 10px; height: auto;">
        <el-row>
          <el-button type="primary" @click="openFormDialog">新建订单</el-button>
          <el-button type="primary" @click="generateWord">生成Word文档</el-button>
        </el-row>
      </el-header>
      <el-main>
        <el-form :model="orderForm" label-width="150px" class="order-form">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="联系人">
                <el-input v-model="orderForm.contact" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="电话">
                <el-input v-model="orderForm.phone" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="产品类型">
                <el-input v-model="orderForm.productType" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="订制方式">
                <el-input v-model="orderForm.orderType" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="样衣数量">
                <el-input-number v-model="orderForm.sampleQty" :min="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="试单数量">
                <el-input-number v-model="orderForm.trialQty" :min="1" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="大货数量">
                <el-input-number v-model="orderForm.bulkQty" :min="1" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="客户情况">
                <el-input v-model="orderForm.customerInfo" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="交期要求">
                <el-input v-model="orderForm.deliveryReq" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="定制细节">
                <el-input v-model="orderForm.customDetails" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="其他需求">
                <el-input v-model="orderForm.otherReq" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item>
            <el-button type="primary" @click="saveOrder">保存</el-button>
          </el-form-item>
        </el-form>
      </el-main>
    </el-container>

    <el-dialog :title="formTitle" :visible.sync="formDialogVisible" width="640px">
      <el-form :model="orderForm" label-width="150px">
        <el-form-item label="联系人">
          <el-input v-model="orderForm.contact" />
        </el-form-item>
        <el-form-item label="产品类型">
          <el-input v-model="orderForm.productType" />
        </el-form-item>
        <el-form-item label="订制方式">
          <el-input v-model="orderForm.orderType" />
        </el-form-item>
        <el-form-item label="样衣数量">
          <el-input-number v-model="orderForm.sampleQty" :min="1" />
        </el-form-item>
        <el-form-item label="试单数量">
          <el-input-number v-model="orderForm.trialQty" :min="1" />
        </el-form-item>
        <el-form-item label="大货数量">
          <el-input-number v-model="orderForm.bulkQty" :min="1" />
        </el-form-item>
        <el-form-item label="客户情况">
          <el-input v-model="orderForm.customerInfo" type="textarea" />
        </el-form-item>
        <el-form-item label="交期要求">
          <el-input v-model="orderForm.deliveryReq" type="textarea" />
        </el-form-item>
        <el-form-item label="定制细节">
          <el-input v-model="orderForm.customDetails" type="textarea" />
        </el-form-item>
        <el-form-item label="其他需求">
          <el-input v-model="orderForm.otherReq" type="textarea" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveOrder">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post } from '@/api/crm/crmm'
import { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, WidthType, AlignmentType, BorderStyle, ShadingType } from 'docx'
import { saveAs } from 'file-saver'

export default {
  name: 'Crmfactoryinquery',
  data() {
    return {
      orderForm: {
        contact: '',
        phone: '',
        productType: '',
        orderType: '',
        sampleQty: 1,
        trialQty: 50,
        bulkQty: 1000,
        customerInfo: '',
        deliveryReq: '',
        customDetails: '',
        otherReq: ''
      },
      formDialogVisible: false,
      formTitle: '新建订单',
      listLoading: false,
      tableHeight: 500
    }
  },
  async mounted() {
    this.calculateTableHeight()
    window.addEventListener('resize', this.calculateTableHeight)

    const orderId = this.$route.params.id // 根据实际情况获取订单ID
    if (orderId) {
      await this.fetchOrder(orderId)
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.calculateTableHeight)
  },
  methods: {
    openFormDialog() {
      this.resetForm()
      this.formTitle = '新建订单'
      this.formDialogVisible = true
    },
    async fetchOrder(orderId) {
      try {
        this.listLoading = true
        const response = await Get(orderId)
        this.orderForm = response.data
      } catch (error) {
        this.$message.error('获取订单信息失败')
      } finally {
        this.listLoading = false
      }
    },
    async saveOrder() {
      try {
        await Post(this.orderForm)
        this.$message.success('保存成功!')
      } catch (error) {
        this.$message.error('保存失败')
      }
    },
    resetForm() {
      this.orderForm = {
        contact: '',
        phone: '',
        productType: '',
        orderType: '',
        sampleQty: 1,
        trialQty: 50,
        bulkQty: 1000,
        customerInfo: '',
        deliveryReq: '',
        customDetails: '',
        otherReq: ''
      }
    },
    generateWord() {
      const doc = new Document({
        sections: [{
          properties: {},
          children: [
            new Paragraph({
              children: [new TextRun({ text: '服装定制单', bold: true, size: 36 })],
              alignment: AlignmentType.CENTER
            }),
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.SINGLE, size: 1 },
                bottom: { style: BorderStyle.SINGLE, size: 1 },
                left: { style: BorderStyle.SINGLE, size: 1 },
                right: { style: BorderStyle.SINGLE, size: 1 },
                insideHorizontal: { style: BorderStyle.SINGLE, size: 1 },
                insideVertical: { style: BorderStyle.SINGLE, size: 1 }
              },
              rows: [
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '产品类型', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({ children: [new Paragraph(this.orderForm.productType)] }),
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '服装订制方式', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({
                      children: [
                        new Paragraph(this.orderForm.orderType),
                        new Paragraph('需求订单，尽量现货')
                      ]
                    })
                  ]
                }),
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '前期试单数量', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({ children: [new Paragraph(this.orderForm.trialQty.toString())] }),
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '大货数量', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({
                      children: [
                        new Paragraph(this.orderForm.bulkQty.toString()),
                        new Paragraph('购买样衣 1套')
                      ]
                    })
                  ]
                }),
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '客户情况', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({
                      children: [
                        new Paragraph('输出国家：'),
                        new Paragraph('产品用途：品牌销售、电商，门店，渠道'),
                        new Paragraph('重点期待：完美复制/交期及时/订单反馈/制作创新'),
                        new Paragraph('运输方式：')
                      ],
                      columnSpan: 3
                    })
                  ]
                }),
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '交期要求', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({
                      children: [
                        new Paragraph(`样品：${this.orderForm.sampleQty} 大货：${this.orderForm.bulkQty}`)
                      ],
                      columnSpan: 3
                    })
                  ]
                })
              ]
            }),
            new Paragraph({
              children: [new TextRun({ text: '定制细节详情', bold: true, size: 28 })],
              spacing: { before: 400, after: 200 }
            }),
            new Paragraph({
              children: [new TextRun(this.orderForm.customDetails)],
              spacing: { after: 200 }
            }),
            new Table({
              width: { size: 100, type: WidthType.PERCENTAGE },
              borders: {
                top: { style: BorderStyle.SINGLE, size: 1 },
                bottom: { style: BorderStyle.SINGLE, size: 1 },
                left: { style: BorderStyle.SINGLE, size: 1 },
                right: { style: BorderStyle.SINGLE, size: 1 },
                insideHorizontal: { style: BorderStyle.SINGLE, size: 1 },
                insideVertical: { style: BorderStyle.SINGLE, size: 1 }
              },
              rows: [
                new TableRow({
                  children: [
                    new TableCell({
                      children: [new Paragraph({ children: [new TextRun({ text: '尺码要求', bold: true })] })],
                      shading: { type: ShadingType.CLEAR, color: 'auto', fill: 'D9D9D9' }
                    }),
                    new TableCell({ children: [new Paragraph('S,M,L,XL 各自多少件')] })
                  ]
                })
              ]
            }),
            new Paragraph({
              children: [new TextRun({ text: '细节要求', bold: true, size: 28 })],
              spacing: { before: 400, after: 200 }
            }),
            new Paragraph({
              children: [new TextRun('1.做工\n2.logo\n3.面辅料\n4.针脚\n5.实物图')],
              spacing: { after: 200 }
            }),
            new Paragraph({
              children: [new TextRun({ text: '其他需求', bold: true, size: 28 })],
              spacing: { before: 400, after: 200 }
            }),
            new Paragraph({
              children: [new TextRun(this.orderForm.otherReq)],
              spacing: { after: 200 }
            }),
            new Paragraph({
              children: [new TextRun({ text: '备注', bold: true, size: 28 })],
              spacing: { before: 400, after: 200 }
            }),
            new Paragraph({
              children: [new TextRun('')],
              spacing: { after: 200 }
            })
          ]
        }]
      })

      Packer.toBlob(doc).then((blob) => {
        saveAs(blob, '服装定制单.docx')
      })
    },

    createInfoTable() {
      return new Table({
        width: { size: 100, type: WidthType.PERCENTAGE },
        borders: {
          top: { style: BorderStyle.SINGLE, size: 1 },
          bottom: { style: BorderStyle.SINGLE, size: 1 },
          left: { style: BorderStyle.SINGLE, size: 1 },
          right: { style: BorderStyle.SINGLE, size: 1 },
          insideHorizontal: { style: BorderStyle.SINGLE, size: 1 },
          insideVertical: { style: BorderStyle.SINGLE, size: 1 }
        },
        rows: [
          this.createTableRow('产品类型', this.orderForm.productType, '服装订制方式', this.orderForm.orderType),
          this.createTableRow('前期试单数量', this.orderForm.trialQty.toString(), '大货数量', this.orderForm.bulkQty.toString()),
          this.createTableRow('客户情况', '输出国家：\n产品用途：品牌销售、电商，门店，渠道\n重点期待：完美复制/交期及时/订单反馈/制作创新\n运输方式：', '', ''),
          this.createTableRow('交期要求', `样品：${this.orderForm.sampleQty} 大货：${this.orderForm.bulkQty}`, '', '')
        ]
      })
    },

    createTableRow(label1, content1, label2, content2) {
      return new TableRow({
        children: [
          new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: label1, bold: true })] })] }),
          new TableCell({ children: [new Paragraph(content1)] }),
          new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: label2, bold: true })] })] }),
          new TableCell({ children: [new Paragraph(content2)] })
        ]
      })
    },

    createDetailsSection(title, content) {
      return [
        new Paragraph({
          children: [new TextRun({ text: title, bold: true, size: 28 })],
          spacing: { before: 400, after: 200 }
        }),
        new Paragraph({
          children: [new TextRun(content)],
          spacing: { after: 200 }
        })
      ]
    },

    createSizingTable() {
      return new Table({
        width: { size: 100, type: WidthType.PERCENTAGE },
        borders: {
          top: { style: BorderStyle.SINGLE, size: 1 },
          bottom: { style: BorderStyle.SINGLE, size: 1 },
          left: { style: BorderStyle.SINGLE, size: 1 },
          right: { style: BorderStyle.SINGLE, size: 1 },
          insideHorizontal: { style: BorderStyle.SINGLE, size: 1 },
          insideVertical: { style: BorderStyle.SINGLE, size: 1 }
        },
        rows: [
          new TableRow({
            children: [
              new TableCell({ children: [new Paragraph({ children: [new TextRun({ text: '尺码要求', bold: true })] })] }),
              new TableCell({ children: [new Paragraph('S,M,L,XL 各自多少件')] })
            ]
          })
        ]
      })
    },
    calculateTableHeight() {
      this.$nextTick(() => {
        const windowHeight = window.innerHeight
        const headerHeight = this.$refs.header ? this.$refs.header.$el.offsetHeight : 0
        const paginationHeight = this.$refs.pagination ? this.$refs.pagination.$el.offsetHeight : 0
        const mainPadding = 60 // el-main 的上下内边距，根据实际情况调整
        this.tableHeight = windowHeight - headerHeight - paginationHeight - mainPadding - 50
      })
    }
  }
}
</script>

<style scoped>
.order-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.el-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.order-form {
  background: #f9f9f9;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.el-form-item {
  margin-bottom: 20px;
}

.dialog-footer {
  text-align: right;
}
</style>
